// 线程的 可连接的 和 可分离的

#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>

using namespace std;

#define THREAD_COUNT 5

void *wait (void *t) {
  // int i;
  // int *tid = (int *)t;
  sleep(1);

  cout << "Sleeping in thread " << endl;
  cout << "Thread with id : " << *(int *)t << "  ...exiting " << endl;

  pthread_exit(NULL);
}

int	main(int argc, char **argv)
{
  int rc;
  int i;
  pthread_t threads[THREAD_COUNT];
  pthread_attr_t attr;

  void *status;

  // NOTE: 初始化并设置线程为可连接的（joinable）
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

  // NOTE: 创建线程,
  for (i = 0; i < THREAD_COUNT; i++)
  {
    cout << "主线程创建子线程： " << i << endl;

    rc = pthread_create(&threads[i], NULL, wait, (void *)&i);

    if (rc)
    {
      cout << "主线程创建子线程失败 " << rc << endl;
      exit(1);
    }
  }


  //NOTE: 删除属性，并等待其他的线程
  pthread_attr_destroy(&attr);

  // NOTE: 连接线程, 等待线程执行完毕
  for (i = 0; i < THREAD_COUNT; i++)
  {
    rc = pthread_join(threads[i], &status);
    if (rc){
        cout << "线程 join 发生错误" << rc << endl;
        exit(-1);
    }
    cout << "Main: completed thread id :" << i << endl;
    cout << "exiting with status :" << status << endl;
  }
  cout << "Main: program exiting." << endl;
  pthread_exit(NULL);
  return 0;
}
